package java6681.task;

import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Junichiro
 * @description
 * @date 2021-04-05 21:18
 **/

public class NoRepeatStudent6681Controller {

    @FXML
    private TextField tfName;

    @FXML
    private TextField tfAge;

    @FXML
    private ListView<Student6681> lvStudent;

    @FXML
    private void initialize() {
        ObservableList<Student6681> items = lvStudent.getItems();
        /*ListView中显示*/
        items.addAll(new Student6681("小张", 22),
                new Student6681("小王", 18),
                new Student6681("牛java", 33));
        /*ListView中的第一项默认已被选中*/
        lvStudent.getSelectionModel().selectFirst();
        /*第一项的姓名和年龄显示在文本框中*/
        tfName.setText("小张");
        tfAge.setText("22");
    }

    @FXML
    void addClick() {
        ObservableList<Student6681> items = lvStudent.getItems();
        /*输入为空*/
        if (tfAge.getText() == null || tfName.getText() == null) {
            return;
        }
        /*姓名没有输入、输入全是空格*/
        if (tfName.getText().trim().isEmpty() || tfAge.getText().trim().isEmpty()) {
            return;
        }
        Student6681 stu = new Student6681();
        stu.setName(tfName.getText().trim());
        stu.setAge(Integer.parseInt(tfAge.getText().trim()));
        /*添加*/
        items.add(stu);
    }

    @FXML
    void changeClick() {
        ObservableList<Student6681> items = lvStudent.getItems();
        /*选中*/
        Student6681 selectedItem = lvStudent.getSelectionModel().getSelectedItem();
        /*查找位置*/
        int i = items.indexOf(selectedItem);
        if (tfAge.getText() == null || tfName.getText() == null) {
            return;
        }
        /*修改*/
        if (i > 0) {
            /*判断输入*/
            if (tfName.getText().trim().isEmpty() || tfAge.getText().trim().isEmpty()) {
                   return;
            }else {
                selectedItem.setName(tfName.getText().trim());
                selectedItem.setAge(Integer.parseInt(tfAge.getText().trim()));
                /*添加修改的内容*/
                items.add(0, selectedItem);
                /*删除*/
                items.remove(0, 1);
            }
        }
    }

    @FXML
    void clearClick() {
        ObservableList<Student6681> items = lvStudent.getItems();
        /*新集合*/
        ArrayList<Student6681> s = new ArrayList<>();

        Iterator<Student6681> it = items.iterator();
        /*判断内容是否重复*/
        while (it.hasNext()) {
            Student6681 next = it.next();
            if (!s.contains(next)) {
                s.add(next);
            }
        }
        /*去除全部内容*/
        items.removeAll(lvStudent.getItems());
        /*添加判断完的新集合*/
        for (Student6681 student6681 : s) {
            System.out.println(student6681);
            items.add(student6681);
        }

    }

}

